package com.koi.common.tree;

import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author ･ᴗ･
 * @description [Tree-此工具类不能放置common层，因为实体类不一样]
 */
public class TreeMenuUtil {

    /**
     * @description [获取父节点]
     */
    public static List<TreeMenu> makeTree(List<TreeMenu> trees) {
        if (!CollectionUtils.isEmpty(trees)) {
            return trees.stream().filter(m -> m.getParentId().equals("0")).peek(
                    (m) -> m.setChildren(getChildrenList(m, trees))
            ).collect(Collectors.toList());
        }
        return null;
    }

    /**
     * @description [获取子节点列表]
     */
    private static List<TreeMenu> getChildrenList(TreeMenu tree, List<TreeMenu> trees) {
        List<TreeMenu> collect = trees.stream().filter(item -> Objects.equals(item.getParentId(), tree.getId())).peek(
                (item) -> item.setChildren(getChildrenList(item, trees))
        ).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(collect)) {
            return collect;
        }
        return null;
    }

    public static void main(String[] args) {
        List<TreeMenu> trees = new ArrayList<>();
        TreeMenu bo1 = new TreeMenu();
        TreeMenu bo2 = new TreeMenu();
        TreeMenu bo3 = new TreeMenu();
        TreeMenu bo4 = new TreeMenu();
        TreeMenu bo5 = new TreeMenu();
        TreeMenu bo6 = new TreeMenu();
        bo1.setId("1");
        bo1.setName("A");
        bo1.setParentId("0");
        bo2.setId("2");
        bo2.setName("AA");
        bo2.setParentId("1");
        bo3.setId("3");
        bo3.setName("AAA");
        bo3.setParentId("2");
        bo4.setId("4");
        bo4.setName("AAAA");
        bo4.setParentId("3");
        bo5.setId("5");
        bo5.setName("B");
        bo5.setParentId("0");
        bo6.setId("6");
        bo6.setName("BB");
        bo6.setParentId("5");
        trees.add(bo1);
        trees.add(bo2);
        trees.add(bo3);
        trees.add(bo4);
        trees.add(bo5);
        trees.add(bo6);
        System.out.println("tree测试：" + TreeMenuUtil.makeTree(trees));
    }
}
